﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.DirectoryServices;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AppTracker
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            fillDatagridview();
        }

        void btnGet_Click(object sender, EventArgs e)
        {
            AddGroupsFromAD();
            fillDatagridview();
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            SaveChanges();
        }

        void frmMain_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            SaveChanges();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'appGroupsDataSet.Instellingen' table. You can move, or remove it, as needed.
            this.instellingenTableAdapter.Fill(this.appGroupsDataSet.Instellingen);
            // TODO: This line of code loads data into the 'appGroupsDataSet.Groepen' table. You can move, or remove it, as needed.
            this.groepenTableAdapter.Fill(this.appGroupsDataSet.Groepen);
        }

        List<string> GetGroups(string strPath)
        {
            DirectoryEntry objADAM = default(DirectoryEntry);
            // Binding object. 
            DirectoryEntry objGroupEntry = default(DirectoryEntry);
            // Group Results. 
            DirectorySearcher objSearchADAM = default(DirectorySearcher);
            // Search object. 
            SearchResultCollection objSearchResults = default(SearchResultCollection);
            // Results collection. 
            
            // Binding path. 
            List<string> result = new List<string>();

            // Get the AD LDS object. 
            try
            {
                objADAM = new DirectoryEntry(strPath);
                objADAM.RefreshCache();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            // Get search object, specify filter and scope, 
            // perform search. 
            try
            {
                objSearchADAM = new DirectorySearcher(objADAM);
                objSearchADAM.Filter = "(&(objectClass=group))";
                objSearchADAM.SearchScope = SearchScope.Subtree;
                objSearchResults = objSearchADAM.FindAll();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            // Enumerate groups 
            try
            {
                if (objSearchResults.Count != 0)
                {
                    foreach (SearchResult objResult in objSearchResults)
                    {
                        objGroupEntry = objResult.GetDirectoryEntry();
                        result.Add(objGroupEntry.Name);
                    }
                }
                else
                {
                    MessageBox.Show("No groups found");
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            return result;
        }

        void AddGroupsFromAD()
        {
            StringBuilder newGroups = new StringBuilder();
            foreach (string path in LdapPaths())
            {
                foreach (string group in GetGroups(path))
                {
                    string groupName = group.Replace("CN=", "");
                    DataRow[] foundRows;
                    foundRows = this.appGroupsDataSet.Tables["Groepen"].Select("Naam = '" + groupName + "'");
                    if (foundRows.Length == 0)
                    {
                        DataRow newGroup = this.appGroupsDataSet.Tables["Groepen"].NewRow();
                        newGroup["Naam"] = group.Replace("CN=", "");
                        newGroup["Uitroltest"] = false;
                        newGroup["Livetest"] = false;
                        newGroup["Afgerond"] = false;
                        this.appGroupsDataSet.Tables["Groepen"].Rows.Add(newGroup);
                        newGroups.Append(group.Replace("CN=", "") + Environment.NewLine);
                    }
                }
            }
            if (newGroups.Length > 0)
            {
                MessageBox.Show("De volgende groepen zijn toegevoegd:" + Environment.NewLine + Environment.NewLine + newGroups);
            }
            else
            {
                MessageBox.Show("Geen nieuwe groepen gevonden.");
            }
        }

        List<string> LdapPaths()
        {
            List<string> result = new List<string>();
            DataRow[] paths;
            paths = this.appGroupsDataSet.Tables["Instellingen"].Select("Naam = 'ldapPath'");
            foreach (DataRow row in paths)
            {
                // MessageBox.Show(row["Waarde"].ToString());
                result.Add(row["Waarde"].ToString());
            }
            return result;
        }

        void SaveChanges()
        {
            this.groepenTableAdapter.Update(this.appGroupsDataSet.Groepen);
        }

        void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            frmAbout aboutBox = new frmAbout();
            aboutBox.Show();
        }

        void fillDatagridview()
        {
            if (cbShowAll.Checked)
            {
                this.groepenBindingSource.RemoveFilter();
            }
            else
            {
                this.groepenBindingSource.Filter = "Afgerond <> 'True'";
            }
        }

        private void cbShowAll_CheckedChanged(object sender, EventArgs e)
        {
            fillDatagridview();
        }
    }
}
